package com.dx.util;
import java.sql.*;

/**
 * jdbc 工具类
 * @Auther: zephyrus
 * @Date: 2023/11/7
 * @Description:
 * @since
 */
public class JdbcUtil {
    /**
     * 驱动程序
     */
    private static final String DRIVER="com.mysql.jdbc.Driver";
    /**
     * 连接字符串
     */
    private final String URL="jdbc:mysql://localhost:3306/db_cms";
    /**
     * 数据库用户名
     */
    private final String USERNAME="root";
    /**
     * 数据库密码
     */
    private final String PASSWORD="root";

    private Connection conn=null;

    private PreparedStatement pst=null;

    private ResultSet rs=null;

    static{
        //加载驱动程序,程序一启动，就加载到内存
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取连接
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL,USERNAME,PASSWORD);
    }

    /**
     * 执行查询
     * select * from demo where id=1 and name='xt'
     * where id=? and name=?
     * @param sql  参数
     * @return
     */
    public ResultSet executeQuery(String sql, Object ... params)  { //Object[] params
        try {
            conn = getConnection();
            pst=conn.prepareStatement(sql);
            if(params!=null) {
                for (int i = 0; i < params.length; i++) {
                    pst.setObject(i + 1, params[i]);
                }
            }
            rs=pst.executeQuery();
        }catch(Exception e){
            e.printStackTrace();
        }
        return rs;
    }

    /**
     * 执行更新 insert,update,delete
     * @param sql
     * @param params
     * @return
     */
    public int executeUpdate(String sql,Object...params){
        int returnValue=0;
        try {
            conn = getConnection();
            pst=conn.prepareStatement(sql);
            if(params!=null) {
                for (int i = 0; i < params.length; i++) {
                    pst.setObject(i + 1, params[i]);
                }
            }
            returnValue=pst.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        }
        return returnValue;
    }

    /**
     * 释放资源
     */
    public void release(){
        try {
            if (rs != null) {
                rs.close();
            }
            if(pst!=null){
                pst.close();
            }
            if(conn!=null){
                conn.close();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

